//
//  TDChooseCarC.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/6.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDChooseCarC.h"
#import "IANActivityIndicatorButton.h"
#import "UIButton+IANActivityView.h"

#import "TDLeftHeadView.h"
#import "TDLeftSectionHeadView.h"
#import "TDRightSectionHeadView.h"
#import "TDLeftCarBrandCell.h"
#import "TDRightCarXiLieCell.h"

#import "NetWorkRequest.h"

@interface TDChooseCarC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *leftTableView;

@property (weak, nonatomic) IBOutlet UITableView *rightTableView;
@property (nonatomic,strong)TDLeftHeadView *leftHeadView;//左侧的头部视图
//@property (nonatomic,strong)NSArray *carBrandArray;//总共的区的数组
//@property (nonatomic,strong)NSArray *carXiLieArray;//每个区的

@property (nonatomic,strong)NSMutableArray *sectionTitleArray;//首字母
@property (nonatomic,strong)NSArray *totalArray;//所有的数组
@property (nonatomic,strong)NSArray *hotCarsArray;//热门车系数组------
@property (nonatomic,strong)NSArray *originHotCarsArray;//热门车系数组------

@property (weak, nonatomic) IBOutlet UILabel *lbe_result;

@property (weak, nonatomic) IBOutlet UIView *view_showResult;

@property (nonatomic,strong)IANActivityIndicatorButton *btn_showResult;

@property (nonatomic,copy)NSString *totalCarNum;

@end

@implementation TDChooseCarC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}


- (void)setupUI {
    //设置导航条
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.tableFooterView = [UIView new];
    [self.leftTableView registerNib:[UINib nibWithNibName:@"TDLeftCarBrandCell" bundle:nil] forCellReuseIdentifier:@"TDLeftCarBrandCellId"];
    self.leftTableView.rowHeight = 50;
    if ([self.leftTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.leftTableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, 100)];
    }
    
    TDLeftHeadView *leftHeadView = [TDLeftHeadView leftHeadView];
    _leftHeadView = leftHeadView;
    __weak typeof(self) weakSelf = self;
    // MARK: - 热门车系按钮点击事件-------
    leftHeadView.leftHeadViewHotCarXiBtnClickBlock = ^{
        weakSelf.selLeftIndexPath = nil;
        weakSelf.selRightIndexPath = nil;
        weakSelf.selModel.brandid = @"0";
        weakSelf.selModel.brandnm = @"热门车系";
        weakSelf.selModel.seriesid = nil;
        weakSelf.selModel.seriesnm = nil;
        [weakSelf resetSelStatus];
        weakSelf.hotCarsArray = weakSelf.originHotCarsArray;
        [weakSelf.leftTableView reloadData];
        [weakSelf.rightTableView reloadData];
        [weakSelf setLeftHeadView];
        [weakSelf setDefaultBtnShow];
    };
    [self setLeftHeadView];
    leftHeadView.frame = CGRectMake(0, 0, Width, 50);
    self.leftTableView.tableHeaderView = leftHeadView;
    self.leftTableView.sectionIndexColor = [UIColor redColor];
    
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    self.rightTableView.tableFooterView = [UIView new];
    [self.rightTableView registerNib:[UINib nibWithNibName:@"TDRightCarXiLieCell" bundle:nil] forCellReuseIdentifier:@"TDRightCarXiLieCellId"];
    self.rightTableView.rowHeight = 50;
    if ([self.rightTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.rightTableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, -10)];
    }
    
    [self setBtnShow];
}

- (void)setBtnShow {
    __weak typeof(self) weakSelf = self;
    _btn_showResult = [[IANActivityIndicatorButton alloc] init];
    _btn_showResult.frame = CGRectMake(0, 5, Width - 40, 40);
    _btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
    _btn_showResult.layer.cornerRadius = 5;
    [_view_showResult addSubview:_btn_showResult];
    [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
    _btn_showResult.TouchBlock = ^(IANActivityIndicatorButton *myButton){
        [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelCarModel = weakSelf.selModel;
        if (weakSelf.chooseCarModelBlock) {
            weakSelf.chooseCarModelBlock(weakSelf.selModel, weakSelf.selLeftIndexPath, weakSelf.selRightIndexPath);
        }
    };
}

- (void)setDefaultBtnShow {
    [_btn_showResult endButtonActivityIndicatorView];
    [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
    _btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
}

- (void)setSelBtnShow {
    [_btn_showResult startButtonActivityIndicatorView];
    [_btn_showResult setTitle:@"加载中" forState:UIControlStateNormal];
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.leftHeadView.frame = CGRectMake(0, 0, Width-100, 50);
    self.leftTableView.tableHeaderView.frame = CGRectMake(0, 0, Width-100, 50);
}

#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.leftTableView) {
        return self.totalArray.count;
    }
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.leftTableView) {
        TDChooseCarModel *model = self.totalArray[section];
        NSArray *tmpArray = model.sortlist;
        return tmpArray.count;
    }
    return self.hotCarsArray.count;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getIdentifier:indexPath tableView:tableView] forIndexPath:indexPath];
    [self setupCell:cell indexPath:indexPath tableView:tableView];
    return cell;
}

- (NSString *)getIdentifier:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    NSString *iden = @"TDLeftCarBrandCellId";
    if (tableView == self.leftTableView) {
        iden = @"TDLeftCarBrandCellId";
    }else {
        iden = @"TDRightCarXiLieCellId";
    }
    return iden;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (tableView == self.leftTableView) {
//        NSArray *tmpArray = @[@"热",@"A",@"B"];
        return self.sectionTitleArray;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.leftTableView) {
        if (_selLeftIndexPath == indexPath) {
            return;
        }
        // MARK: - 清除右侧的所有颜色  不要用记录上次的来清除  -----------
        for (TDChooseCarModel *model in self.totalArray) {
            for (TDChooseCarBrandModel *tmpBrandModel in model.sortlist) {
                for (TDChooseSubCarModel *tmpSubModel in tmpBrandModel.sublist) {
                    tmpSubModel.isSel = NO;
                }
            }
        }
        TDChooseCarModel *model = self.totalArray[indexPath.section];
        NSArray *tmpArray = model.sortlist;
        
        for (TDChooseCarModel *model in self.totalArray) {
            for (TDChooseCarBrandModel *tmpBrandModel in model.sortlist) {
                tmpBrandModel.isSel = NO;
            }
        }
        // MARK: - 这种清除方法容易出现bug---------
//        if (self.selLeftIndexPath) {
//            TDChooseCarModel *model = self.totalArray[self.selLeftIndexPath.section];
//            NSArray *tmpArray = model.sortlist;
//            TDChooseCarBrandModel *tmpBrandModel = tmpArray[self.selLeftIndexPath.row];
//            tmpBrandModel.isSel = NO;
//        }
        TDChooseCarBrandModel *brandModel = tmpArray[indexPath.row];
        self.hotCarsArray = brandModel.sublist;
        brandModel.isSel = YES;
        self.selLeftIndexPath = indexPath;
        self.selRightIndexPath = nil;
        self.selModel.brandid = brandModel.brandid;
        self.selModel.brandnm = brandModel.brandnm;
        self.selModel.seriesid = nil;
        self.selModel.seriesnm = nil;
        [self setLeftHeadView];
        [self.leftTableView reloadData];
        [self.rightTableView reloadData];
        
    }else {
        // MARK: - 这里不要做点击想同indexPath的判断------因为数据源已经完全改变了----------
        for (TDChooseCarModel *model in self.totalArray) {
            for (TDChooseCarBrandModel *tmpBrandModel in model.sortlist) {
                for (TDChooseSubCarModel *tmpSubModel in tmpBrandModel.sublist) {
                    tmpSubModel.isSel = NO;
                }
            }
        }
        TDChooseSubCarModel *tmpCheXiModel = self.hotCarsArray[indexPath.row];
        tmpCheXiModel.isSel = YES;
        [self.rightTableView reloadData];
        self.selRightIndexPath = indexPath;
        self.selModel.seriesid = tmpCheXiModel.seriesid;
        self.selModel.seriesnm = tmpCheXiModel.seriesnm;
    }
    
    if (self.selLeftIndexPath) {
        //加载网络数据
        [self loadAllCarSourceListNetData];
    }else {
        [_btn_showResult setTitle:@"显示结果" forState:UIControlStateNormal];
        return;
    }
    
}

- (void)setupCell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (tableView == self.leftTableView) {
        TDChooseCarModel *model = self.totalArray[indexPath.section];
        NSArray *tmpArray = model.sortlist;
        TDLeftCarBrandCell *leftCarBrandCell = (TDLeftCarBrandCell *)cell;
        TDChooseCarBrandModel *brandModel = tmpArray[indexPath.row];
        if (brandModel.isSel) {
            leftCarBrandCell.contentView.backgroundColor = [UIColor whiteColor];
        }else {
            leftCarBrandCell.contentView.backgroundColor = [UIColor colorWithHex:0xf5f5f5];
        }
        leftCarBrandCell.lbe_carBrand.text = brandModel.brandnm;
    }else {
        TDRightCarXiLieCell *rightCarXiLieCell = (TDRightCarXiLieCell *)cell;
        TDChooseSubCarModel *subModel = self.hotCarsArray[indexPath.row];
        if (subModel.isSel) {
            rightCarXiLieCell.lbe_carXiLie.textColor = [UIColor colorWithHex:0xbf0021];
        }else {
            rightCarXiLieCell.lbe_carXiLie.textColor = [UIColor blackColor];
        }
        rightCarXiLieCell.lbe_carXiLie.text = subModel.seriesnm;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == self.leftTableView) {
        TDLeftSectionHeadView *leftHeadView = [TDLeftSectionHeadView leftSectionHeadView];
        TDChooseCarModel *model = self.totalArray[section];
        leftHeadView.lbe_carBigBrand.text = model.sortnm;
        return leftHeadView;
    }
    TDRightSectionHeadView *rightHeadView = [TDRightSectionHeadView rightSectionHeadView];
    if (self.selLeftIndexPath) {
        TDChooseCarModel *model = self.totalArray[self.selLeftIndexPath.section];
        rightHeadView.lbe_rightSectionTitle.text = self.selModel.brandnm;
    }else {
        rightHeadView.lbe_rightSectionTitle.text = @"热门车系";
    }
    return rightHeadView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.rightTableView) {
        return 50;
    }
    return 26;
}



// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
    
}


// MARK: - 获取网络数据-----从登录地方获取了  这个地方不获取了-----
- (void)loadNetData {
    NSDictionary *response = [HelpObject getDocumentDicStrPath:kBasicMessageFilePath];
    
    //        data是一个数组----------------我真是个智障额....
    // MARK: - 卧槽这个data怎么又变成object了----改来改去也不说下-------
    NSArray *tmpCarbrandsArray = response[@"data"][@"carbrands"];
    NSArray *tmpHotCarsArray = response[@"data"][@"hotcars"][@"sortlist"];
    self.totalArray = [NSArray yy_modelArrayWithClass:[TDChooseCarModel class] json:tmpCarbrandsArray].mutableCopy;
    self.sectionTitleArray = [NSMutableArray array];
    for (TDChooseCarModel *totalModel in self.totalArray) {
        [self.sectionTitleArray addObject:totalModel.sortby];
    }
    
    if (!self.hotCarsArray) {
       self.hotCarsArray = [NSArray yy_modelArrayWithClass:[TDChooseSubCarModel class] json:tmpHotCarsArray].mutableCopy;
    }
    
    self.originHotCarsArray = [NSArray yy_modelArrayWithClass:[TDChooseSubCarModel class] json:tmpHotCarsArray].mutableCopy;
    
    if (self.selLeftIndexPath) {
        TDChooseCarModel *model = self.totalArray[self.selLeftIndexPath.section];
        NSArray *tmpArray = model.sortlist;
        TDChooseCarBrandModel *tmpBrandModel = tmpArray[self.selLeftIndexPath.row];
        NSArray *tmpXiLieArray = tmpBrandModel.sublist;
        self.hotCarsArray = tmpXiLieArray;
        tmpBrandModel.isSel = YES;
        if (self.selRightIndexPath) {
            TDChooseSubCarModel *tmpXiLieModel = tmpXiLieArray[self.selRightIndexPath.row];
            tmpXiLieModel.isSel = YES;
        }
    }
    
    [self.leftTableView reloadData];
    [self.rightTableView reloadData];
    
    if (self.selLeftIndexPath) {
        [self.leftTableView scrollToRowAtIndexPath:self.selLeftIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        if (self.selRightIndexPath) {
            [self.rightTableView scrollToRowAtIndexPath:self.selRightIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
    }
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
}

- (void)setLeftHeadView {
    //非选中状态-----
    if (_selLeftIndexPath) {
        _leftHeadView.lbe_headTitle.textColor = [UIColor blackColor];
        _leftHeadView.bgView.backgroundColor = [UIColor colorWithHex:0xf5f5f5];
        
    }else {
        _leftHeadView.lbe_headTitle.textColor = [UIColor colorWithHex:0xbf0021];
        _leftHeadView.bgView.backgroundColor = [UIColor whiteColor];
    }
}

- (TDChooseSelectedModel *)selModel {
    if (!_selModel) {
        _selModel = [[TDChooseSelectedModel alloc] init];
    }
    return _selModel;
}

// MARK: - 显示结果按钮点击事件------
- (IBAction)showResultBtnClick:(UIButton *)sender {
    [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelCarModel = _selModel;
    if (self.chooseCarModelBlock) {
        self.chooseCarModelBlock(_selModel, _selLeftIndexPath, _selRightIndexPath);
    }
}

- (void)resetSelStatus {
    // MARK: - 清除右侧的所有颜色  不要用记录上次的来清除  -----------
    for (TDChooseCarModel *model in self.totalArray) {
        for (TDChooseCarBrandModel *tmpBrandModel in model.sortlist) {
            for (TDChooseSubCarModel *tmpSubModel in tmpBrandModel.sublist) {
                tmpSubModel.isSel = NO;
            }
        }
    }
    for (TDChooseCarModel *model in self.totalArray) {
        for (TDChooseCarBrandModel *tmpBrandModel in model.sortlist) {
            tmpBrandModel.isSel = NO;
        }
    }
}

- (IBAction)closeBtnClick:(UIButton *)sender {
    if (self.chooseCarCloseBtnClickBlock) {
        self.chooseCarCloseBtnClickBlock();
    }
}

- (IBAction)cleanBtnClick:(UIButton *)sender {
    self.selLeftIndexPath = nil;
    self.selRightIndexPath = nil;
    self.selModel.brandid = nil;
    self.selModel.brandnm = nil;
    self.selModel.seriesid = nil;
    self.selModel.seriesnm = nil;
    [self resetSelStatus];
    [self setLeftHeadView];
    [self.leftTableView reloadData];
    [self.rightTableView reloadData];
    self.lbe_result.text = @"显示结果";
}


// MARK: - 获取网络数据-----
- (void)loadAllCarSourceListNetData {
//    [NetWorkRequest cancel];
    [self setSelBtnShow];
    // MARK: - 获取车源列表--------------
    if (!_locationModel) {
        self.noticeText = @"定位失败,请稍后重试";
        return;
    }
    if ([HelpObject isBlankString:[AppSetting shareAppSetting].topcompanyid]) {
        self.noticeText = @"顶级公司id为空";
        return;
    }
    self.selStoreModel = [TDCarSourceAllMessageModel shareAllMessageModel].carsourceSelStoreModel;
    NSString *topcompanyid = [AppSetting shareAppSetting].topcompanyid;
    NSMutableDictionary *parDic = @{@"topcompanyid":topcompanyid,
                                    @"longitude":_locationModel.longitude,
                                    @"latitude":_locationModel.latitude,
                                    @"prevrows":@"0",
                                    @"showrows":@"1",
                                    }.mutableCopy;
    [self setParaDic:parDic];
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:CarListTD parmeters:parDic response:^(NSDictionary *response) {
        [weakSelf.btn_showResult endButtonActivityIndicatorView];
        weakSelf.btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
        if (response) {
            weakSelf.totalCarNum = [HelpObject changeNull:response[@"data"][@"total"]];
            NSString *tmpStr = [NSString stringWithFormat:@"显示%@车源",weakSelf.totalCarNum];
            [weakSelf.btn_showResult setTitle:tmpStr forState:UIControlStateNormal];
        }else {
        }
    } netError:^(NSError *error) {
        [weakSelf.btn_showResult endButtonActivityIndicatorView];
        weakSelf.btn_showResult.backgroundColor = [UIColor colorWithHex:0xbf0021];
    }];
}


- (void)setParaDic:(NSMutableDictionary *)paraDic {
    
    NSString *tmpWorkdayf = [_selDateModel.yearStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    NSString *tmpWorkdayT = [_selDateModel.yearEndStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    
    [paraDic setValue:[HelpObject changeNull:tmpWorkdayf] forKey:@"workdayf"];
    [paraDic setValue:[HelpObject changeNull:tmpWorkdayT] forKey:@"workdayt"];
    [paraDic setValue:[HelpObject changeNull:_selStoreModel.searchStoreModel.storeid] forKey:@"storeid"];
    
    [paraDic setValue:[HelpObject changeNull:_selModel.brandid] forKey:@"brandid"];
    
    [paraDic setValue:[HelpObject changeNull:_tf_search_str] forKey:@"cartype"];
    [paraDic setValue:[HelpObject changeNull:_selModel.seriesid] forKey:@"seriesid"];
    [paraDic setValue:[TDCarSourceAllMessageModel shareAllMessageModel].orders forKey:@"orders"];
}

@end
